package data.dao;

import security.access.AccessChecker;
import security.crypto.CipherFactory;

import data.io.FileIO;
import data.model.Data;

public abstract class DAO {
	
	private final AccessChecker accessChecker;
	
	public DAO(AccessChecker accessChecker){
		this.accessChecker = accessChecker;
	}
	
	public Data accessData(String path){
		if(accessChecker.checkAccess(path, AccessChecker.READ, this))
			return readData(path);
		
		throw new SecurityException("Access not granted for reading : "+path);
	}
	
	public void saveData(String path, Data data, boolean decrypt){
		if(accessChecker.checkAccess(path, AccessChecker.WRITE, this))
			writeData(path,data,decrypt);
		else
			throw new SecurityException("Access not granted for writing in : "+path);
	}
	
	protected void writeData(String path, Data data, boolean decrypt){
		if(decrypt)
			FileIO.write(path, CipherFactory.getCipher().decrypt(data));
		else
			FileIO.write(path, data);
	}
	
	protected abstract Data readData(String path);
}
